package com.yonyou.brigade.util.operateutil;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * Created by Administrator on 2018/10/23.
 */
@Service
public class RedisUtils {
    @Autowired
    private StringRedisTemplate template;

    //设置值
    public  void setKey(String key,String value){
        try {
            ValueOperations<String, String> ops = template.opsForValue();
            ops.set(key,value);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //设置值 (expireTime 有效时间)
    public  void setKey(String key,String value,Integer expireTime){
        try {
            ValueOperations<String, String> ops = template.opsForValue();
            ops.set(key,value,expireTime, TimeUnit.MINUTES);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //获取值
    public String getValue(String key){
        String result = "";
        try {
            ValueOperations<String, String> ops = template.opsForValue();
            result = ops.get(key);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    //删除
    public Boolean delKey(String key){
        Boolean result = null;
        try {
            result = template.delete(key);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    //获取有效时间
    public Long getExpire(String key){
        Long expireTime = null;
        try {
            expireTime = template.getExpire(key);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return expireTime;
    }

    //判断key 是否存在
    public Boolean hasKey(String key){
        Boolean b = null;
        try {
            b = template.hasKey(key);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return b;
    }

    //设置失效时间
    public Boolean setExpire(String key,Integer timeout){
        Boolean b = null;
        try {
            b = template.expire(key, timeout, TimeUnit.MINUTES);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return b;
    }
}